package com.llb666.shop.order.api.controller;

import com.llb666.common.core.utils.DateUtil;
import com.llb666.shop.order.infracore.mq.RabbitSender;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 消息测试api
 *
 * @author llb666
 */
@Tag(name = "消息测试api")
@RestController
@RequestMapping("rabbit-mq")
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class MqTestController {

    private final RabbitSender rabbitSender;
    private final StreamBridge streamBridge;

    @Operation(summary = "发送消息")
    @PostMapping("/send")
    public String send() throws InterruptedException {
        Map<String, Object> properties = new HashMap<>();
        properties.put("llb", "hah");
        rabbitSender.send("hello", properties);
        Thread.sleep(10000);
        return "message send ok";
    }

    @Operation(summary = "商品减库存")
    @GetMapping("/decreaseStock")
    public String decreaseStock() {
        Map<String, Object> map = new HashMap<>();
        map.put("itemSpecId", "bingan-1001-spec-3");
        map.put("buyCounts", 1);
        Message<Map<String,Object>> message = MessageBuilder.withPayload(map).build();
        streamBridge.send("orderGroup-out-0", message);
        Map<String, Object> payload = message.getPayload();
        return "商品规格Id : " + payload.get("itemSpecId") + ",减少库存" + payload.get("buyCounts");
    }


    @Operation(summary = "发送延时消息")
    @PostMapping("/delay")
    public String delay(String orderId) {
        // "7d39ae08506640688737fd83058427e8"
        Message<String> message = MessageBuilder.withPayload(orderId)
                .setHeader("x-delay", 5 * 1000)
                .build();
        streamBridge.send("delay-out-0", message);
        System.out.println("/delay：发送时间" + DateUtil.dateToStringWithTime());
        return "SUCCESS";
    }
}
